package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.business.*;
import com.ys.entity.finance.TcwAccountCountForCompany;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.storage.*;
import com.ys.mapper.storage.*;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.storage.TccFbaBoxUpService;
import com.ys.service.storage.TccFbaPlanService;
import com.ys.service.storage.TccStockControlService;
import com.ys.util.FbaUtils;
import com.ys.util.RedisUtil;
import com.ys.util.shiro.BeanUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import io.swagger.client.model.Item;
import io.swagger.client.model.ListShipmentItemsResponse;
import io.swagger.client.model.Shipment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-04
 * @Description: FBA计划单实现层
 * @Version: 1.5
 */
@Service("tccFbaPlanService")
public class TccFbaPlanServiceImpl implements TccFbaPlanService {
    private static final Logger logger = LoggerFactory.getLogger(TccFbaPlanServiceImpl.class);

    @Autowired
    private TccStockControlService tccStockControlService;

    @Autowired
    private TccFbaPlanMapper tccFbaPlanMapper;

    @Autowired
    private TccFbaPlanItemMapper tccFbaPlanItemMapper;

    @Autowired
    private TccFbaLogisticsMethodMapper tccFbaLogisticsMethodMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private TccFbaFeeDetailsMapper tccFbaFeeDetailsMapper;

    @Autowired
    private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

    @Autowired
    private FbaInboundApiService fbaInboundApiService;

    @Autowired
    private TccFbaBoxUpService tccFbaBoxUpService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 新增
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, Long menuId) throws Exception {
        //判断网店-物流方式不允许为空
        if (params.get("shopId") == null){
            return R.error("网店名称不允许为空!");
        }
        if (params.get("logsticsWayId") == null){
            return R.error("物流方式不允许为空!");
        }
        TccFbaPlan entity = JSON.parseObject(JSON.toJSONString(params),TccFbaPlan.class);
        if (entity.getCreationMethod() == 0){
            if (entity.getEvenlyBoxNum() > 0){
                return R.error("均分箱数不允许大于0箱!");
            }
        }else {
            if (entity.getDeliverState() == 0){
                if (entity.getEvenlyBoxNum() < 5 && entity.getEvenlyBoxNum() != 0){
                    return R.error("均分箱数不允许小于5箱!");
                }
            }
        }
        entity.setStatus(TccFbaPlanEnum.Status.EMPTY.value);//状态
        entity.setEffectStock(0);//审批状态

        //获取制单人信息
        TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
        if(tsUserChange!=null){
            entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
        }else {
            return R.error("未查询到制单人信息！");
        }
        tccFbaPlanMapper.insert(entity);

        R r = pdParams(params, entity);
        if (r.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r.getMsg());
        }
        YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, entity.getBid(), createUserId);
        }

        return R.ok(AddDto.gotoEdit("/web/storage/tccFbaPlan/toEdit?bid=" + entity.getBid()));
    }


    /**
     * 修改fba计划单
     * @param params
     * @param menuId
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R toEdit(Map<String, Object> params, Long menuId) throws Exception {
        //判断网店-物流方式不允许为空
        if (params.get("shopId") == null){
            return R.error("网店名称不允许为空!");
        }
        if (params.get("logsticsWayId") == null){
            return R.error("物流方式不允许为空!");
        }
        TccFbaPlan entity = JSON.parseObject(JSON.toJSONString(params),TccFbaPlan.class);
        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(entity.getBid()).queryFirst();
        if (tccFbaPlan == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        if (entity.getCreationMethod() == 0){
            if (entity.getEvenlyBoxNum() > 0){
                return R.error("均分箱数不允许大于0箱!");
            }
        }else {
            if (entity.getDeliverState() == 0){
                if (entity.getEvenlyBoxNum() < 5 && entity.getEvenlyBoxNum() != 0){
                    return R.error("均分箱数不允许小于5箱!");
                }
            }
        }

        tccFbaPlanMapper.update(entity);

        //删除子表数据..并且解冻库存
        R r1 = delItem( entity);
        if (r1.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r1.getMsg());
        }

        R r = pdParams(params, entity);
        if (r.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r.getMsg());
        }
        return R.ok(AddDto.gotoEdit("/web/storage/tccFbaPlan/toEdit?bid=" + entity.getBid()));
    }

    /**
     * 删除
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R deleteTrue( Long id) throws Exception {
        if (id == null) {
            return R.error("ID不能为空");
        }

        TccFbaPlan entity = new TccFbaPlan().setId(id).queryFirst();
        if (entity == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
            return R.error("已生效数据无法删除");
        }

        TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
        if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
            //冻结资金
            tcwAccountCountForCompanyService.thaw(
                    entity.getVgsbm(),
                    tccFbaFeeDetails.getPriceTranPredict(),
                    TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                    tccFbaFeeDetails.getId(),
                    entity.getBid(),
                    entity.getBid()
            );
        }

        //删除子表数据..并且解冻库存
        R r1 = delItem( entity);
        if (r1.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r1.getMsg());
        }

        tccFbaPlanMapper.deleteTrue(entity.getId());

        String loginUserId = ShiroUtils.getUserId();
        yspTaskService.flowDelete(entity.getBid(), loginUserId);
        return R.ok(EditDto.closeAndReload());
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowPass(Long id, String loginUserId) throws Exception {
        TccFbaPlan entity = new TccFbaPlan().setId(id).queryFirst();
        if (entity == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        String bid = entity.getBid();

        YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
        if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(entity.getBid()).queryList();
            Map<String,Object> mapBoolean = new HashMap<String, Object>();
            Map<String, List<String>> mapBoolean1 = new HashMap<String,  List<String>>();
            for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
                if (tccFbaPlanItem.getIsSign().equals("是")){
                    if (mapBoolean1.get(tccFbaPlanItem.getSku()) == null){
                        if(tccFbaPlanItem.getAnnexFile() != null && !tccFbaPlanItem.getAnnexFile().equals("")){
                            List<String> annexFileList = new ArrayList<>();
                            annexFileList.add(tccFbaPlanItem.getAnnexFile());
                            mapBoolean1.put(tccFbaPlanItem.getSku(),annexFileList);
                        }
                    }else {
                        if(tccFbaPlanItem.getAnnexFile() != null && !tccFbaPlanItem.getAnnexFile().equals("")){
                            List<String> annexFileList = (mapBoolean1.get(tccFbaPlanItem.getSku()));
                            annexFileList.add(tccFbaPlanItem.getAnnexFile());
                            mapBoolean1.put(tccFbaPlanItem.getSku(),annexFileList);
                        }else {
                        }
                    }
                }
            }

            for (Map.Entry<String, List<String>> entry : mapBoolean1.entrySet()) {
                List<String> valueList = entry.getValue();
                if (valueList.size() == 0) {
                    return R.error("FBA计划单存在透明标签附件未上传,请核实后再操作!");
                }else if (valueList.size() > 2){
                    return R.error("SKU:"+entry.getKey()+"透明标签附件上传重复,请核实后再操作!");
                }
            }
        }
        try {
            Flow f = yspTaskService.flowPass(bid, loginUserId);
            if (f.getCode() == Flow.Code.FAILED.value) {
                return R.error(f.getMsg());
            } else {
                if (f.getState() == Flow.State.FINISH.value) {
                    entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
                    tccFbaPlanMapper.update(entity);
                }
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {
        TccFbaPlan entity = new TccFbaPlan().setId(id).queryFirst();
        if (entity == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        String bid = entity.getBid();

        return yspTaskService.flowRefuse(bid, reason, ShiroUtils.getUserId());
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowInit(Long id, String reason, String loginUserId) throws Exception {
        TccFbaPlan entity = new TccFbaPlan().setId(id).queryFirst();
        if (entity == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        String bid = entity.getBid();
        return yspTaskService.flowInit(bid, reason, ShiroUtils.getUserId());
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flow(Long id) throws Exception {
        TccFbaPlan entity = new TccFbaPlan().setId(id).queryFirst();
        if (entity == null){
            return R.error("FBA计划单不存在,请核实后再操作!");
        }
        if (entity.getStatus() != TccFbaPlanEnum.Status.EMPTY.value) {
            return R.error("FBA计划单货件状态不为无的数据无法审核!");
        }
        if (entity.getEffectStock() != FlowEnum.EffectStock.EFFECTED.value) {
            return R.error("FBA计划单未生效数据无法审核!");
        }
        //手动直接审核通过
        if (entity.getCreationMethod() == 0){
            //获取制单人信息
            TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
            String auditingUser = null;
            Date auditingTime = null;
            if(tsUserChange!=null){
                auditingUser = tsUserChange.getUserId() + '/' + tsUserChange.getUserName();
                auditingTime = new Date();
            }else {
                return R.error("未查询到制单人信息！");
            }
            entity.setStatus(TccFbaPlanEnum.Status.ISAUDITED.value);
            entity.setAuditingUser(auditingUser);
            entity.setAuditingTime(auditingTime);
            tccFbaPlanMapper.update(entity);

            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(entity.getBid()).queryList();
            List<TccFbaBoxUpItemByAdd> tccFbaBoxUpItemByAdds = new ArrayList<>();
            List<TccFbaBoxUpByAdd> tccFbaBoxUpByAddList = new ArrayList<>();
            TccFbaBoxUpByAdd tccFbaBoxUpByAdd = new TccFbaBoxUpByAdd();
            List<TccFbaBoxUpInfoByAdd> tccFbaBoxUpInfoByAdds = new ArrayList<>();
            TccFbaBoxUpInfoByAdd tccFbaBoxUpInfoByAdd = new TccFbaBoxUpInfoByAdd();
            tccFbaBoxUpInfoByAdds.add(tccFbaBoxUpInfoByAdd);

            for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
                TccFbaBoxUpItemByAdd tccFbaBoxUpItemByAdd = new TccFbaBoxUpItemByAdd();
                tccFbaBoxUpItemByAdd.setFbaPlanItemId(tccFbaPlanItem.getId());
                tccFbaBoxUpItemByAdd.setAsin(tccFbaPlanItem.getAsin());
                tccFbaBoxUpItemByAdds.add(tccFbaBoxUpItemByAdd);
            }
            tccFbaBoxUpInfoByAdd.setGoodsInfoList(tccFbaBoxUpItemByAdds);
            tccFbaBoxUpByAdd.setFbaOrPackInfoList(tccFbaBoxUpInfoByAdds);
            tccFbaBoxUpByAddList.add(tccFbaBoxUpByAdd);

//            //新增装箱数据
            R r = tccFbaBoxUpService.addOneFbaBoxInfo(tccFbaBoxUpByAddList,entity.getBid());
            if (r.getCode() != 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error(r.getMsg());
            }
        }else {
            if(redisUtil.get(entity.getBid())!= null && !"".equals(entity.getBid())){
                return R.error("不允许重复点击");
            }
            if (entity.getInboundPlanId() != null) {
                if (!entity.getInboundPlanId().equals("")){
                    return R.error("FBA计划单数据已经产生API动作,无法审核,请核实后再操作!");
                }
                return R.error("FBA计划单数据已经产生API动作,无法审核,请核实后再操作!");
            }
            redisUtil.set(entity.getBid(),"0");
            //发货计划
            if (entity.getDeliverState() == 0){
                //0按箱自动发货
                R r = fbaInboundApiService.boxDelivery(entity);
                if (r.getCode() != 0){
                    redisUtil.delete(entity.getBid());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(r.getMsg());
                }
                redisUtil.delete(entity.getBid());
            }else {
//                //1按SKU自动发货
//                Integer  count = new TccFbaInboundApiLog()
//                .setPid(entity.getId().toString())
//                        .setBid(entity.getBid())
//                        .setType("listPlacementOptions")
//                        .count();
//                if (count == 0){
//                    R r = fbaInboundApiService.skuDelivery(entity);
//                    if (r.getCode() != 0){
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        return R.error(r.getMsg());
//                    }
//                }else {
//                    return R.ok("已生成");
//                }

                //测试流程 正式切换上面动作
                return R.ok();
            }
        }
        return R.ok("审核成功!");
    }

    /**
     * 计划审核-sku生成装箱单
     * @param params 具体的货件预览信息
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowCreate(Map<String, Object> params) throws Exception {
        if (params == null){
            return R.error("货件方案未选择,不允许计划审核!");
        }
        String bid = params.get("bid").toString();
        TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bid).queryFirst();
        if (tccFbaPlan == null){
            return R.error("FBA计划单不存在,不允许计划审核！");
        }

        if (params.get("dataPost") == null){
            return R.error("货件方案未选择,不允许计划审核!");
        }
        JSONObject dataPost = JSON.parseObject(params.get("dataPost").toString());
        if (dataPost.get("placementOptionId") == null){
            return R.error("placementOptionId未选择,不允许计划审核!");
        }
        Integer conut = new TccFbaBoxUp().setBidFbaPlan(bid).count();
        if (conut != 0){
            return R.error("已计划审核,不允许重复审核!");
        }

        //请求api设置放置选项
        R r = fbaInboundApiService.confirmPlacementOption(tccFbaPlan,dataPost.get("placementOptionId").toString());
        if (r.getCode() != 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(r.getMsg());
        }
        TccFbaInboundApiLog tccFbaInboundApiLog = new TccFbaInboundApiLog()
                .setPid(tccFbaPlan.getId().toString())
                .setBid(tccFbaPlan.getBid())
                .setType("listPlacementOptions")
                .queryFirst();

        List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(tccFbaPlan.getBid()).queryList();

        if (tccFbaInboundApiLog != null){
            Map<String, List<TccFbaBoxUpInfoByAdd>> shipmentMap = new HashMap<>();
            JSONObject resultJO = JSON.parseObject(tccFbaInboundApiLog.getJsonResult());
            JSONArray conditionJA = JSON.parseArray(resultJO.get("placementOptions").toString());
            BigDecimal fee = BigDecimal.ZERO;
            for (int i = 0; i < conditionJA.size(); i++) {
                JSONObject JO = conditionJA.getJSONObject(i);
                //选择fba方案
                if (!JO.get("placementOptionId").toString().equals(dataPost.get("placementOptionId").toString())){
                    continue;
                }
                JSONArray shipmentIds = JSON.parseArray(JO.get("shipmentIds").toString());
                JSONArray fees = JSON.parseArray(JO.get("fees").toString());
                //查询货件详情
                for (int j = 0; j < shipmentIds.size(); j++) {
                    String  shipmentId = shipmentIds.get(j).toString();
                    TccFbaInboundApiLog shipmentLog = new TccFbaInboundApiLog()
                            .setPid(shipmentId)
                            .setBid(tccFbaPlan.getBid())
                            .setType("getShipment")
                            .queryFirst();
                    if (shipmentLog == null){
                        continue;
                    }
                    Shipment shipment = JSON.parseObject(shipmentLog.getJsonResult(), Shipment.class);
                    List<TccFbaBoxUpInfoByAdd> tccFbaBoxUpInfoByAdds = new ArrayList<>();
                    TccFbaBoxUpInfoByAdd tccFbaBoxUpInfoByAdd = new TccFbaBoxUpInfoByAdd();
                    tccFbaBoxUpInfoByAdd.setFbaNo(shipment.getShipmentConfirmationId());
                    tccFbaBoxUpInfoByAdd.setFbaTrackNo(shipment.getAmazonReferenceId());
                    tccFbaBoxUpInfoByAdd.setFbaToken(null);
                    tccFbaBoxUpInfoByAdd.setFbaId(shipmentId);
                    tccFbaBoxUpInfoByAdd.setFbaWarehouse(shipment.getDestination().getWarehouseId());
                    if (shipment.getDestination().getAddress() != null){
                        io.swagger.client.model.Address address = shipment.getDestination().getAddress();
                        tccFbaBoxUpInfoByAdd.setFbaWarehouseAddr(address.getPostalCode());
                    }
                    for (int k = 0; k < fees.size(); k++) {
                        JSONObject feeJs = fees.getJSONObject(k);
                        if (feeJs.get("target").equals("Placement Services")){
                            JSONObject feeValue = JSON.parseObject(feeJs.get("value").toString());
                            if (feeValue.size() != 0){
                                fee = new BigDecimal(feeValue.get("amount").toString());
                            }
                        }
                    }
                    tccFbaBoxUpInfoByAdd.setFbaAmount(fee.compareTo(BigDecimal.ZERO) == 0?null:fee);

                    TccFbaInboundApiLog listShipmentItemsLog = new TccFbaInboundApiLog()
                            .setPid(shipmentId)
                            .setBid(tccFbaPlan.getBid())
                            .setType("listShipmentItems")
                            .queryFirst();
                    ListShipmentItemsResponse listShipmentItemsResponse = JSON.parseObject(listShipmentItemsLog.getJsonResult(), ListShipmentItemsResponse.class);
                    List<TccFbaBoxUpItemByAdd> getGoodsInfoList = new ArrayList<>();
                    for (Item item : listShipmentItemsResponse.getItems()){
                        //查询出来商品信息
                        List<TccFbaPlanItem> tccFbaPlanItemListNew = tccFbaPlanItemList.stream().filter(tccFbaPlanItem -> item.getAsin().equals(tccFbaPlanItem.getAsin())
                                && item.getFnsku().equals(tccFbaPlanItem.getFnSku())
                                && item.getMsku().equals(tccFbaPlanItem.getSku()))
                                .collect(Collectors.toList());
                        if (tccFbaPlanItemListNew.size() !=0){
                            TccFbaBoxUpItemByAdd tccFbaBoxUpItemByAdd = new TccFbaBoxUpItemByAdd();
                            tccFbaBoxUpItemByAdd.setFbaPlanItemId(tccFbaPlanItemListNew.get(0).getId());
                            tccFbaBoxUpItemByAdd.setAsin(item.getAsin());
                            tccFbaBoxUpItemByAdd.setBoxUpNum(item.getQuantity());
                            getGoodsInfoList.add(tccFbaBoxUpItemByAdd);
                        }
                    }
                    tccFbaBoxUpInfoByAdd.setGoodsInfoList(getGoodsInfoList);
                    tccFbaBoxUpInfoByAdds.add(tccFbaBoxUpInfoByAdd);

                    if (shipmentMap.get(shipment.getDestination().getWarehouseId()) == null){
                        shipmentMap.put(shipment.getDestination().getWarehouseId(),tccFbaBoxUpInfoByAdds);
                    }else {
                        List<TccFbaBoxUpInfoByAdd> list = shipmentMap.get(shipment.getDestination().getWarehouseId());
                        for (TccFbaBoxUpInfoByAdd tccFbaBoxUpInfoByAdd1 : tccFbaBoxUpInfoByAdds){
                            list.add(tccFbaBoxUpInfoByAdd1);
                        }
                    }
                }
            }

            List<TccFbaBoxUpByAdd> tccFbaBoxUpByAddList = new ArrayList<>();
            //Lambda表达式
            List<TccFbaBoxUpByAdd> finalTccFbaBoxUpByAddList = tccFbaBoxUpByAddList;
            shipmentMap.forEach((k, v) ->{
                System.out.println(k+"====="+v);
                TccFbaBoxUpByAdd tccFbaBoxUpByAdd = new TccFbaBoxUpByAdd();
                tccFbaBoxUpByAdd.setPlacementOptionId(dataPost.get("placementOptionId").toString());

                List<TccFbaBoxUpInfoByAdd> list = shipmentMap.get(k);

                tccFbaBoxUpByAdd.setFbaOrPackInfoList(list);
                finalTccFbaBoxUpByAddList.add(tccFbaBoxUpByAdd);
            });

            //新增装箱数据
            r = tccFbaBoxUpService.addOneFbaBoxInfo(tccFbaBoxUpByAddList,tccFbaPlan.getBid());
            if (r.getCode() != 0){
                return R.error(r.getMsg());
            }
        }
        return R.ok("审核成功");
    }

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R delete(Map<String, Object> params) throws Exception {
        //生效+货件状态为空，才可以删除
        if (params.get("list") == null) {
            return R.error("选择数据不能为空!");
        }
        String[] strs = params.get("list").toString().split(",");
        Set<String> bidList = new HashSet<>();
        for(String bid : strs){
            bidList.add(bid);
        }

        for (String bid :bidList) {
            TccFbaPlan entity = new TccFbaPlan().setBid(bid).queryFirst();
            if (entity == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("FBA计划单不存在,请核实后再操作!");
            }
            if (entity.getEffectStock() != FlowEnum.EffectStock.EFFECTED.value) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("未生效数据无法计划取消!");
            }
            if (entity.getStatus() != TccFbaPlanEnum.Status.EMPTY.value) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("货件状态不为无的数据无法计划取消!");
            }
            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(entity.getBid()).queryList();
            for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
                //解冻流水
                tccStockControlService.thaw(
                        tccFbaPlanItem.getStockControlId(),
                        tccFbaPlanItem.getNumPlanDeliver(),
                        TccStockFrozenRunningEnum.SourceType.TCC_FBAPLAN_FINISH.value,
                        entity.getBid(),
                        entity.getId());
            }
            TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
            if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
                //冻结资金
                tcwAccountCountForCompanyService.thaw(
                        entity.getVgsbm(),
                        tccFbaFeeDetails.getPriceTranPredict(),
                        TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                        tccFbaFeeDetails.getId(),
                        entity.getBid(),
                        entity.getBid()
                );
            }

            entity.setStatus(TccFbaPlanEnum.Status.CANCELED.value);
            tccFbaPlanMapper.update(entity);
        }
        return R.ok("计划取消成功!");
    }

    /**
     * 删除子表数据..并且解冻库存
     */
    private R delItem(TccFbaPlan entity){
        try {
            List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(entity.getBid()).queryList();
            for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
                //解冻流水
                tccStockControlService.thaw(
                        tccFbaPlanItem.getStockControlId(),
                        tccFbaPlanItem.getNumPlanDeliver(),
                        TccStockFrozenRunningEnum.SourceType.TCC_FBAPLAN_FINISH.value,
                        entity.getBid(),
                        entity.getId());
                tccFbaPlanItemMapper.deleteTrue(tccFbaPlanItem.getId());
            }
            TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
            if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
                //冻结资金
                tcwAccountCountForCompanyService.thaw(
                        entity.getVgsbm(),
                        tccFbaFeeDetails.getPriceTranPredict(),
                        TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                        tccFbaFeeDetails.getId(),
                        entity.getBid(),
                        entity.getBid()
                );
            }
            tccFbaFeeDetailsMapper.deleteTrue(tccFbaFeeDetails.getId());

            TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod().setSourceBid(entity.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
            tccFbaLogisticsMethodMapper.deleteTrue(tccFbaLogisticsMethod.getId());

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 判断参数
     * @return
     */
    private R pdParams(Map<String, Object> params,TccFbaPlan entity){
        try {

            TccLogisticsMethod tccLogisticsMethod = new TccLogisticsMethod().setId(Long.valueOf(params.get("logsticsWayId").toString())).queryFirst();
            if (tccLogisticsMethod.getCoefficientWeight() == 0){
                tccLogisticsMethod.setCoefficientWeight(5000);
            }else {
                tccLogisticsMethod.setCoefficientWeight(6000);
            }

            TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(entity.getShopId()).queryFirst();
            if (tpAmazonShop.getPhone() == null || tpAmazonShop.getPhone().equals("")) {
                return R.error("Amazon店铺管理电话未维护!");
            }
            if (tpAmazonShop.getName() == null || tpAmazonShop.getName().equals("")){
                return R.error("Amazon店铺管理仓库名称未维护!");
            }
            if (tpAmazonShop.getAddressLine1() == null || tpAmazonShop.getAddressLine1().equals("")){
                return R.error("Amazon店铺管理仓库地址1未维护!");
            }
            if (tpAmazonShop.getCity() == null || tpAmazonShop.getCity().equals("")){
                return R.error("Amazon店铺管理城市未维护!");
            }
            if (tpAmazonShop.getCity() == null || tpAmazonShop.getCity().equals("")){
                return R.error("Amazon店铺管理城市未维护!");
            }
            if (tpAmazonShop.getStateOrProvinceCode() == null || tpAmazonShop.getStateOrProvinceCode().equals("")){
                return R.error("Amazon店铺管理县区级未维护!");
            }
            if (tpAmazonShop.getPostalCode() == null || tpAmazonShop.getPostalCode().equals("")){
                return R.error("Amazon店铺管理邮编未维护!");
            }

            //根据店铺是否欧代标判断 （打印欧盟标使用）
            if (tpAmazonShop.getEuStatus() == 1) {
                if (tpAmazonShop.getEuAgent() == null || tpAmazonShop.getEuAgent().equals("")){
                    return R.error("Amazon店铺管理欧盟代理人未维护!");
                }
                if (tpAmazonShop.getEuAgentAddress() == null || tpAmazonShop.getEuAgentAddress().equals("")){
                    return R.error("Amazon店铺管理欧盟代理地址未维护!");
                }
                if (tpAmazonShop.getManufacturerAddress() == null || tpAmazonShop.getManufacturerAddress().equals("")){
                    return R.error("Amazon店铺管理制造商地址未维护!");
                }
                if (tpAmazonShop.getManufacturer() == null || tpAmazonShop.getManufacturer().equals("")){
                    return R.error("Amazon店铺管理制造商未维护!");
                }
            }

            //运输类型维护
            TccTransportationType tccTransportationType = new TccTransportationType()
                    .addLeftJoin("TCC_TransportationTypeItem B ON B.TransportationTypeId = A.id")
                    .where("B.TransportationTypeZbCn = " + tccLogisticsMethod.getTransportationId())
                    .queryFirst();
            //自动 - 按SUK发货 自动选择FREIGHT_LTL 发货
            if (entity.getCreationMethod() == 1 && entity.getDeliverState() == 1){
                tccTransportationType = new TccTransportationType()
                        .setTransportationTypeEn("FREIGHT_LTL").queryFirst();
            }

            //查询运营公司备案
            ThrOperateCompanyApply drOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(entity.getVgsbm()).queryFirst();
            if (drOperateCompanyApply.getVgsSh() == null || drOperateCompanyApply.getVgsSh().equals("")) {
                throw new RuntimeException("公司名称和税号不能为空，请维护!");
            }


            //查询仓库信息
            TccWarehouse tccWarehouse = new TccWarehouse().setCck(tccLogisticsMethod.getCck()).queryFirst();

            //计重梯度+抛重梯度
            List<TccLogisticsMethodItem> tccLogisticsMethodItemList = new TccLogisticsMethodItem()
                    .setMethodId(tccLogisticsMethod.getId())
                    .queryList();
            //计重梯度
            List<TccLogisticsMethodItem> jzTdList  = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.JZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());
            //抛重梯度
            List<TccLogisticsMethodItem> pzTdList  = tccLogisticsMethodItemList.stream().filter(tccLogisticsMethodItem ->
                    TccLogisticsMethodItemEnum.LogisticsMethodType.PZTD.value.equals(tccLogisticsMethodItem.getLogisticsMethodType())).collect(Collectors.toList());

            List<TccLogisticsMethodItemSon> czTdList = new TccLogisticsMethodItemSon()
                    .setMethodId(tccLogisticsMethod.getId())
                    .queryList();

            //报关
            HashSet<Integer> declarationStateList = new HashSet<Integer>();
            //品名数量
            Set<String> gradeNum = new HashSet<>();
            //SKU
            Set<String> skuList = new HashSet<>();
            //仓库SKU是否统一
            Map<String, Object> chwSkuList = new HashMap<>();
            //实重（kg）
            BigDecimal weightReal = BigDecimal.ZERO;
            //抛重（kg）
            BigDecimal weightVol = BigDecimal.ZERO;
            //计重（kg）
            BigDecimal weightCal = BigDecimal.ZERO;

            //计重梯度
            BigDecimal jfStart = BigDecimal.ZERO;
            BigDecimal jfEnd = BigDecimal.ZERO;
            BigDecimal jfFee = BigDecimal.ZERO;

            //抛重梯度
            BigDecimal pzStart = BigDecimal.ZERO;
            BigDecimal pzEnd = BigDecimal.ZERO;
            BigDecimal pzFee = BigDecimal.ZERO;

            List<TccLogisticsMethodItem> tdjzPrice;

            List<TccLogisticsMethodItem> tdPzPrice;
            //超出品名数量
            Integer exceedNum = 0;
            //api发货数量
            int numApiDeliver = 0;
            //材质费用
            BigDecimal czFee = BigDecimal.ZERO;
            String czCn = "";
            String czEn = "";

            //保存列表信息
            if (params.get("subData") != null) {
                JSONArray subData = JSON.parseArray(params.get("subData").toString());
                if (subData.size() == 0){
                    return R.error("FBA计划单子表数据不允许为空!");
                }


                //api平均分的总数
                Map<String,Integer> apiNumTol = new HashMap<>();
                //实际商品总数
                Map<String,Integer> apiNum = new HashMap<>();
                //判断是否有多条库存
                Map<String,List<Integer>> apiNumList = new HashMap<>();
                if (entity.getCreationMethod() == 1){
                    if (entity.getEvenlyBoxNum() != 0){
                        for (int i = 0; i < subData.size(); i++) {
                            JSONObject jSONObject = subData.getJSONObject(i);
                            TccFbaPlanItem tccFbaPlanItem = JSON.parseObject(JSON.toJSONString(jSONObject), TccFbaPlanItem.class);
                            String name = tccFbaPlanItem.getCommodityCode() + tccFbaPlanItem.getSku();
                            Integer numPlanDeliver = 0;
                            if (tccFbaPlanItem.getNumPlanDeliver() != null && !tccFbaPlanItem.getNumPlanDeliver().equals("")){
                                numPlanDeliver = tccFbaPlanItem.getNumPlanDeliver();
                            }
                            if (apiNumTol.get(name) != null){
                                apiNumTol.put(name,new Integer(apiNumTol.get(name).toString()) + numPlanDeliver);
                                List<Integer> numList = apiNumList.get(name);
                                numList.add(numPlanDeliver);
                                apiNumList.put(name,numList);
                            }else {
                                apiNumTol.put(name,numPlanDeliver);
                                List<Integer> numList = new ArrayList<>();
                                numList.add(numPlanDeliver);
                                apiNumList.put(name,numList);
                            }
                        }

                        Set keySet =apiNumTol.keySet();
                        for(Object key : keySet ) {
                            Object value = apiNumTol.get(key);
                            double result = Math.ceil((double)new Integer(value.toString()) / entity.getEvenlyBoxNum());
                            apiNum.put(key.toString(),(int) result * entity.getEvenlyBoxNum());
                        }
                    }
                }

                for (int i = 0; i < subData.size(); i++) {
                    logger.info("开始新增FBA计划:"+entity.getBid()+"单商品序号:"+i);

                    JSONObject jSONObject = subData.getJSONObject(i);
                    TccFbaPlanItem tccFbaPlanItem = JSON.parseObject(JSON.toJSONString(jSONObject), TccFbaPlanItem.class);
                    if (jSONObject.get("numPlanDeliver") == null || jSONObject.getInteger("numPlanDeliver") == null || jSONObject.getInteger("numPlanDeliver") == 0 ) {
                        return R.error("计划发货数量不允许为0或者为空！");
                    }
                    if (jSONObject.get("sku") == null) {
                        return R.error("SKU不允许为空！");
                    }
                    if (jSONObject.get("fnSku") == null) {
                        return R.error("FNSKU不允许为空！");
                    }
                    TpAmazonShopProduct tpAmazonShopProduct = new TpAmazonShopProduct().setShopId(entity.getShopId()).setSellerSku(jSONObject.get("sku").toString()).queryFirst();
                    if (tpAmazonShopProduct == null){
                        return R.error("商品SKU不允许为空！");
                    }
                    if (tpAmazonShopProduct.getMainImage() == null || tpAmazonShopProduct.getMainImage().equals("")) {
                        return R.error("图片主图信息为空,请至Amazon商品管理，重新获取商品信息");
                    }
                    if (tpAmazonShopProduct.getFnSku() == null || tpAmazonShopProduct.getFnSku().equals("")) {
                        return R.error("FnSku为空,请至Amazon商品管理，重新获取商品信息");
                    }
                    if (tpAmazonShopProduct.getPackageLength() == null || tpAmazonShopProduct.getPackageLength().equals("")) {
                        return R.error("包装长度为空,请至Amazon商品管理，重新获取商品信息");
                    }
                    if (tpAmazonShopProduct.getPackageWidth() == null || tpAmazonShopProduct.getPackageWidth().equals("")) {
                        return R.error("包装宽度为空,请至Amazon商品管理，重新获取商品信息");
                    }
                    if (tpAmazonShopProduct.getPackageHeight() == null || tpAmazonShopProduct.getPackageHeight().equals("")) {
                        return R.error("包装高度为空,请至Amazon商品管理，重新获取商品信息");
                    }

                    TpProductActive tpProductActive = new TpProductActive().setCode(jSONObject.get("commodityCode").toString()).queryFirst();
                    if (tpProductActive.getCommodityPlId() == null){
                        return R.error(tpProductActive.getName() + ",商品品类为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (tpProductActive.getCodeHs() == null){
                        return R.error(tpProductActive.getName() + ",海关编码为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (tpProductActive.getNameUnitId() == null){
                        return R.error(tpProductActive.getName() + ",商品单位为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (tpProductActive.getNameId() == null){
                        return R.error(tpProductActive.getName() + ",商品品名为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (tpProductActive.getUsageId() == null){
                        return R.error(tpProductActive.getName() + ",商品用途为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (tccFbaPlanItem.getNameMaterialCn() == null) {
                        return R.error(tpProductActive.getName() + ",商品材质为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    if (new TpProductActiveComponent().setPcode(tpProductActive.getCode()).where("A.LinkIn IS NULL").count() != 0){
                        return R.error(tpProductActive.getName() + ",采购链接为空,请至Listing库，完整维护商品物流发票信息");
                    }
                    //长宽高不能为0
                    if (jSONObject.get("heightPackage").equals(0) || jSONObject.get("widthPackage").equals(0) || jSONObject.get("lengthPackage").equals(0)){
                        return R.error(tpProductActive.getName() + ",请至Listing库，完整维护商品物流发票信息(商品尺寸不允许为0)");
                    }
                    if (jSONObject.get("weightPackage").equals(0)){
                        return R.error(tpProductActive.getName() + ",请至Listing库，完整维护商品物流发票信息(商品重量不允许为0)");
                    }
                    //判断材质
                    List<TpProductMaterial> tpProductMaterialList = new TpProductMaterial().setProductCode(tpProductActive.getCode()).queryList();
                    if (tpProductMaterialList.size() == 0){
                        return R.error(tpProductActive.getName() + ",请至Listing库，完整维护商品物流发票信息(商品材质未维护)");
                    }
                    if (jSONObject.get("priceIn") == null) {
                        return R.error(tpProductActive.getName() + ",该库存缺少采购价,请联系客服人员修改后再操作!");
                    }
                    //计算api发货数量
                    if (entity.getCreationMethod() == 1){
                        if (entity.getEvenlyBoxNum() == 0){
                            //自动+非均分拆箱=计划发货数量
                            numApiDeliver = tccFbaPlanItem.getNumPlanDeliver();
                        }else {
                            String name = tccFbaPlanItem.getCommodityCode() + tccFbaPlanItem.getSku();

                            Integer num = new Integer(apiNum.get(name));
                            Integer numTol = new Integer(apiNumTol.get(name));

                            if (numTol.equals(num) && apiNumList.get(name).size() == 1){
                                //自动+均分拆箱=（计划发货数量/均分箱数--向上取整）*均分箱数
                                double result = Math.ceil((double)tccFbaPlanItem.getNumPlanDeliver() / entity.getEvenlyBoxNum());

                                numApiDeliver =  (int) result * entity.getEvenlyBoxNum();
                            }else {
                                //不相等就扣减数量直至为0
                                apiNumTol.put(name,numTol - tccFbaPlanItem.getNumPlanDeliver());
                                if (numTol > tccFbaPlanItem.getNumPlanDeliver()){
                                    numApiDeliver = tccFbaPlanItem.getNumPlanDeliver();
                                    apiNum.put(name,num - tccFbaPlanItem.getNumPlanDeliver());
                                }else {
                                    numApiDeliver = num;
                                }
                            }
                        }
                    }
                    tccFbaPlanItem.setNumApiDeliver(numApiDeliver);
                    tccFbaPlanItem.setImg(tpProductActive.getImg());
                    declarationStateList.add(tccFbaPlanItem.getDeclarationItemState());
                    //不一样的品名数=(商品中文、海关编码、材质中文只要一个不同)
                    String join = tccFbaPlanItem.getNameGoodsCn() + '-' + tccFbaPlanItem.getCodeGoodsHs() + '-' + tccFbaPlanItem.getNameMaterialCn();
                    gradeNum.add(join);
                    skuList.add(tccFbaPlanItem.getSku());

                    //不一样的仓库库存=(SKU、ASIN、FNSKU、仓库只要一个不同)
                    String chwSku = tccFbaPlanItem.getSku() + '-' + tccFbaPlanItem.getAsin() + '-' + tccFbaPlanItem.getFnSku();
                    if (chwSkuList.get(chwSku) != null ){
                        if (!chwSkuList.get(chwSku).equals(tccFbaPlanItem.getChw())){
//                            return R.error("该SKU:"+tccFbaPlanItem.getSku()+"不允许多个仓库,请处理后再操作!");
                        }
                    }
                    chwSkuList.put(chwSku,tccFbaPlanItem.getChw());
                    //判断是否是混合材质
                    if (tccFbaPlanItem.getNameMaterialCn().indexOf(",") == -1) {
                        //赋值材质附加费(取最大值)
                        for (int j = 0; j < czTdList.size(); j++) {
                            if (czTdList.get(j).getMaterialNameCn().equals(tccFbaPlanItem.getNameMaterialCn())) {
                                if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                                    czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                                    czCn = (czTdList.get(j).getMaterialNameCn());
                                    czEn = (czTdList.get(j).getMaterialNameEn());
                                }
                            }
                        }
                    } else {
                        String[] nameMaterialCnList = tccFbaPlanItem.getNameMaterialCn().split(",");
                        for (String nameMaterialCn : nameMaterialCnList){
                            for (int j = 0; j < czTdList.size(); j++) {
                                if (czTdList.get(j).getMaterialNameCn().equals(nameMaterialCn)) {
                                    if (czTdList.get(j).getAdditionalMaterialBilling().compareTo(czFee) > 0) {
                                        czFee = (czTdList.get(j).getAdditionalMaterialBilling());
                                        czCn = (czTdList.get(j).getMaterialNameCn());
                                        czEn = (czTdList.get(j).getMaterialNameEn());
                                    }
                                }
                            }
                        }
                    }
                    //冻结流水
                    tccStockControlService.frozen(
                            tccFbaPlanItem.getStockControlId(),
                            tccFbaPlanItem.getNumPlanDeliver(),
                            TccStockFrozenRunningEnum.SourceType.TCC_FBAPLAN_PASS.value,
                            entity.getBid(),
                            entity.getId());

                    //（商品重量*计划发货数量）之和
                    weightReal = weightReal.add((tccFbaPlanItem.getWeightPackage().multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()))).setScale(2, RoundingMode.HALF_UP));
                    //（商品包装尺寸相乘*计划发货数量/抛货系数）之和
                    weightVol = weightVol.add((tccFbaPlanItem.getLengthPackage().multiply(tccFbaPlanItem.getWidthPackage()).multiply(tccFbaPlanItem.getHeightPackage()).multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver())))
                            .divide(new BigDecimal(tccLogisticsMethod.getCoefficientWeight()), 2, RoundingMode.HALF_UP));
                    tccFbaPlanItem.setBidFbaPlan(entity.getBid());
                    tccFbaPlanItem.setNumRealityBox(0);
                    tccFbaPlanItemMapper.insert(tccFbaPlanItem);
                }
                if (declarationStateList.size() > 1) {
                    return R.error("非报关商品和报关商品不能下同一个FBA计划!");
                }
                if (gradeNum.size() > tccLogisticsMethod.getMaxProNameNum()) {
                    return R.error("实际品名数量:" + gradeNum.size() + ",大于品名上限数量:" + tccLogisticsMethod.getMaxProNameNum());
                }
                if (entity.getCreationMethod() == 1){
                    if (skuList.size() > 25) {
                        return R.error("下单方式:自动,SKU一次性不能超过25个!");
                    }
                }

                weightReal = weightReal.divide(new BigDecimal(1000),2,BigDecimal.ROUND_HALF_UP);//克转千克保留2位小数，四舍五入
                //MAX（实重,抛重）
                weightCal = weightReal.max(weightVol);
                //约分规则
                if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO1.value){
                    weightCal = new BigDecimal(Math.ceil(weightCal.doubleValue()));
                }else if (tccLogisticsMethod.getDivisionalRule() == TccLogisticsMethodEnum.DivisionalRule.INTO_05_1.value){
                    weightCal = FbaUtils.precision(weightCal);
                }
                //MAX【单箱起重（kg），单票起重（kg）】
                weightCal = weightCal.max(tccLogisticsMethod.getSinglePassCrane());
                weightCal = weightCal.max(tccLogisticsMethod.getWeightCalBySingle());

                //计重梯度价（￥/kg） 参照“计重”对应范围的梯度价
                BigDecimal finalWeightCal = weightCal;
                tdjzPrice = jzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                        && finalWeightCal.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());

                //计重
                if (tdjzPrice.size() != 0){
                    jfStart = tdjzPrice.get(0).getHeavySn();
                    jfEnd =tdjzPrice.get(0).getHeavyEn();
                    jfFee = tdjzPrice.get(0).getPrice();
                }

                //抛重附加费（￥/kg） 参照“抛重-实重”对应范围的梯度价
                BigDecimal finalWeightVol = weightVol.subtract(weightReal);
                tdPzPrice = pzTdList.stream().filter(tccLogisticsMethodItem -> finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavySn()) >= 0
                        && finalWeightVol.compareTo(tccLogisticsMethodItem.getHeavyEn()) <= 0).collect(Collectors.toList());
                //抛重
                if (tdPzPrice.size() != 0){
                    pzStart = tdPzPrice.get(0).getHeavySn();
                    pzEnd =tdPzPrice.get(0).getHeavyEn();
                    pzFee = tdPzPrice.get(0).getPrice();
                }
            } else {
                return R.error("列表信息为空！");
            }



            //新增FBA物流维护
            TccFbaLogisticsMethod tccFbaLogisticsMethod = new TccFbaLogisticsMethod();
            BeanUtils.copyProperties(tccLogisticsMethod,tccFbaLogisticsMethod);
            tccFbaLogisticsMethod.setId(null);
            tccFbaLogisticsMethod.setLogsticsWayId(tccLogisticsMethod.getId());
            tccFbaLogisticsMethod.setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value);
            tccFbaLogisticsMethod.setSourceBid(entity.getBid());
            tccFbaLogisticsMethod.setTransportationCn(tccTransportationType.getTransportationTypeCn());
            tccFbaLogisticsMethod.setTransportationEn(tccTransportationType.getTransportationTypeEn());
            tccFbaLogisticsMethod.setVck(tccWarehouse.getVck());
            //计重
            tccFbaLogisticsMethod.setJfStart(jfStart);
            tccFbaLogisticsMethod.setJfEnd(jfEnd);
            tccFbaLogisticsMethod.setJfFee(jfFee);

            //抛重
            tccFbaLogisticsMethod.setPzStart(pzStart);
            tccFbaLogisticsMethod.setPzEnd(pzEnd);
            tccFbaLogisticsMethod.setPzFee(pzFee);

            //材质
            tccFbaLogisticsMethod.setCzFee(czFee);
            tccFbaLogisticsMethod.setCzCn(czCn);
            tccFbaLogisticsMethod.setCzEn(czEn);
            //目的地
            tccFbaLogisticsMethod.setWarehouseArea("空");
            tccFbaLogisticsMethod.setFirstPostalCode("空");
            tccFbaLogisticsMethod.setWarehouseCode("空");
            tccFbaLogisticsMethod.setAdditionalBilling("0");
            tccFbaLogisticsMethodMapper.insert(tccFbaLogisticsMethod);

            TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails();
            tccFbaFeeDetails.setWeightReal(weightReal);
            tccFbaFeeDetails.setWeightVol(weightVol);
            tccFbaFeeDetails.setWeightCal(weightCal);
            //预估计重费（￥）=计重（kg）*【计重梯度价（￥/kg）+抛重附加费（￥/kg）+目的地附加计费（￥/kg）】
            tccFbaFeeDetails.setPriceTranCalWeight((tccFbaLogisticsMethod.getJfFee().add(tccFbaLogisticsMethod.getPzFee())).multiply(weightCal).setScale(2, BigDecimal.ROUND_HALF_UP));
            tccFbaFeeDetails.setNumProName(gradeNum.size());
            //（品名数量-免费品名数量）+负数取0】* 品名附加计费标准（￥/个)
            exceedNum = gradeNum.size()-tccFbaLogisticsMethod.getFreeProNameNum();
            tccFbaFeeDetails.setPriceProNameExtraPredict(exceedNum>0?
                    (new BigDecimal(exceedNum).multiply(tccFbaLogisticsMethod.getAdditionalStandardAmount())).setScale(2, BigDecimal.ROUND_HALF_UP)
                    :BigDecimal.ZERO);
            tccFbaFeeDetails.setPriceQualityExtra(czCn);
            //预估材质附加费（￥）=计重*材质附加计费（￥/kg）
            tccFbaFeeDetails.setPriceQualityExtraPredict((czFee.multiply(weightCal)).setScale(2, BigDecimal.ROUND_HALF_UP));
            //预估附加费（￥） = 预估品名附加费（￥）+预估材质附加费（￥）
            tccFbaFeeDetails.setPriceExtraPredict(tccFbaFeeDetails.getPriceProNameExtraPredict().add(
                    tccFbaFeeDetails.getPriceQualityExtraPredict()
            ));
            tccFbaFeeDetails.setSourceType(TccFbaFeeDetailsEnum.SourceType.PLAN.value);
            tccFbaFeeDetails.setSourceBid(entity.getBid());
            //预估物流费（总）=预估计重费（￥）+预估附加费（￥）+清关服务费(￥)
            tccFbaFeeDetails.setPriceTranPredict(tccFbaFeeDetails.getPriceTranCalWeight().add(tccFbaFeeDetails.getPriceExtraPredict()).add(tccFbaLogisticsMethod.getClearanceOpeAmount()));
            tccFbaFeeDetails.setStatus(1);
            tccFbaFeeDetails.setVgsbm(entity.getVgsbm());
            tccFbaFeeDetailsMapper.insert(tccFbaFeeDetails);

            //账户资金+负载额度+5000< 预估物流费用
            TcwAccountCountForCompany accountCountForCompany = new TcwAccountCountForCompany().setVGsBm(entity.getVgsbm()).queryFirst();
            if (accountCountForCompany.getFJe().add(accountCountForCompany.getFFzEd()).add(new BigDecimal(5000)).compareTo(tccFbaFeeDetails.getPriceTranPredict()) == -1){
                return R.error("资金不足,请核实后再操作!");
            }
            if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
                try {
                    //冻结资金
                    tcwAccountCountForCompanyService.frozen(
                            entity.getVgsbm(),
                            tccFbaFeeDetails.getPriceTranPredict(),
                            TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
                            tccFbaFeeDetails.getId(),
                            entity.getBid(),
                            entity.getBid());
                }catch (Exception e){
                    return R.error(e.getMessage());
                }
            }

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
        return R.ok();
    }


}
